<template>
  <div>
    <!--列表-->
    <el-table :data="tableRoleList">
      <el-table-column prop="name" label="名字" />
      <el-table-column prop="description" label="角色" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button
            type="primary"
            size="small"
            @click="alertTheDisable(scope.row)"
          >
            修改菜单
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分配菜单的对话框
// tree组件添加ref属性，后期方便进行tree组件对象的获取
-->
    <el-dialog v-model="dialogMenuVisible" title="分配菜单" width="40%">
      <el-form label-width="80px">
        <el-tree
          :data="sysMenuTreeList"
          ref="tree"
          show-checkbox
          default-expand-all
          :check-on-click-node="true"
          node-key="id"
          :props="defaultProps"
        />
        <el-form-item>
          <el-button type="primary" @click="alertTheTreeValue">提交</el-button>
          <el-button @click="dialogMenuVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import {
  findSysRolePermissionByRoleId,
  roleList,
  saveNewMenuFromRole,
} from '@/api/userManager'
import { ElMessage } from 'element-plus'

const tableRoleList = ref([])
const defaultProps = {
  children: 'children',
  label: 'name',
}
const saveNewMenuFromRoleModel = ref({
  roleId: '',
  menuList: [],
})
const roleId = ref('')
const dialogMenuVisible = ref(false)
const sysMenuTreeList = ref([])
// 树对象变量
const tree = ref()
const findRoleList = () => {
  roleList().then(res => {
    tableRoleList.value = res.data
  })
}
const alertTheDisable = async dataRow => {
  dialogMenuVisible.value = true
  roleId.value = dataRow.id
  const { data } = await findSysRolePermissionByRoleId(dataRow.id)
  console.log(data)
  sysMenuTreeList.value = data.sysMenuList
  tree.value.setCheckedKeys(data.roleMenuIds) // 进行数据回显
}

const alertTheTreeValue = async () => {
  const roleMenuIds = tree.value.getCheckedKeys()
  saveNewMenuFromRoleModel.value.menuList = roleMenuIds
  saveNewMenuFromRoleModel.value.roleId = roleId.value
  console.log(saveNewMenuFromRoleModel.value)
  const { code, data, message } = await saveNewMenuFromRole(
    saveNewMenuFromRoleModel.value
  )
  if (code === 200) {
    ElMessage.success(message)
    dialogMenuVisible.value = false
    findRoleList()
  } else {
    ElMessage.error('修改失败！')
  }
}

findRoleList()
</script>

<style scoped></style>
